<script setup>

import { dayjs, ElMessage, ElMessageBox, ElNotification, genFileId } from 'element-plus'
import { getCurrentRouteQuery } from '@/utils/routerUtils'
import { h, ref } from 'vue'
import {
  addRequireDocumentApi,
  deleteRequireApi,
  deleteRequireDocumentApi,
  downLoadRequireDocumentApi,
  findRequireDetailsApi,
  findUserByNameApi,
  updateRequireApi
} from '@/apis/projectManagement'
import { useUserStore } from '@/store'
import { Link as IconLink, Plus as IconPlus } from '@element-plus/icons-vue'
import router from '@/router'
import Progress from '@/components/progress/index.vue'

const query = getCurrentRouteQuery()
const userStore = useUserStore()
const requireDetailsRequest = ref({
  task: {}
})
const requireDetailsResponse = ref({
  creator: {},
  updateTime: null
})
const editDisable = ref(true)
console.log(query)
const schemeDisable = ref(true)

const ownerSearchLoading = ref(true)
const ownerList = ref([])
findUserByNameApi('').then(({data}) => {
  ownerList.value = data || []
})
const onOwnerRemoteMethod = (name) => {
  ownerSearchLoading.value = true
  findUserByNameApi(name).then(({data}) => {
    ownerList.value = data || []
  }).finally(() => {
    ownerSearchLoading.value = false
  })
}

findRequireDetailsApi({id: query.id}).then(({data}) => {
  requireDetailsRequest.value.name = data.name
  requireDetailsRequest.value.owner = data.owner.id
  requireDetailsRequest.value.task = data.task
  requireDetailsRequest.value.id = data.id
  requireDetailsRequest.value.status = data.status
  requireDetailsRequest.value.startTime = dayjs(data.startTime).format('YYYY-MM-DD HH:mm:ss')
  requireDetailsRequest.value.endTime = dayjs(data.endTime).format('YYYY-MM-DD HH:mm:ss')
  requireDetailsRequest.value.description = data.description
  requireDetailsRequest.value.priority = data.priority
  requireDetailsRequest.value.scheme = data.scheme
  requireDetailsResponse.value = data
  console.log(data)
})

const onRequireDetailsSubmit = () => {
  console.log(requireDetailsRequest.value)
  requireDetailsRequest.value.taskId = requireDetailsRequest.value.task.id
  requireDetailsRequest.value.startTime = dayjs(requireDetailsRequest.value.startTime).format('x')
  requireDetailsRequest.value.endTime = dayjs(requireDetailsRequest.value.endTime).format('x')

  updateRequireApi(requireDetailsRequest.value).then(res => {
    ElMessage.success('修改成功！')
    editDisable.value = true
    findRequireDetailsApi({id: query.id}).then(({data}) => {
      requireDetailsRequest.value.name = data.name
      requireDetailsRequest.value.owner = data.owner.id
      requireDetailsRequest.value.task = data.task
      requireDetailsRequest.value.id = data.id
      requireDetailsRequest.value.status = data.status
      requireDetailsRequest.value.startTime = dayjs(data.startTime).format('YYYY-MM-DD HH:mm:ss')
      requireDetailsRequest.value.endTime = dayjs(data.endTime).format('YYYY-MM-DD HH:mm:ss')
      requireDetailsRequest.value.description = data.description
      requireDetailsRequest.value.priority = data.priority
      requireDetailsRequest.value.scheme = data.scheme
      requireDetailsResponse.value = data
      console.log(data)
    })
  })
}

const onRequireSchemeSubmit = () => {
  requireDetailsRequest.value.taskId = requireDetailsRequest.value.task.id
  requireDetailsRequest.value.startTime = dayjs(requireDetailsRequest.value.startTime).format('x')
  requireDetailsRequest.value.endTime = dayjs(requireDetailsRequest.value.endTime).format('x')
  updateRequireApi(requireDetailsRequest.value).then(res => {
    ElMessage.success('修改成功！')
    schemeDisable.value = true
  })
}

const GoTo = (task) => {
  router.push(`/system/projectManagement/projectTask/projectTaskDetails?taskId=${ task.id }&groupId=${ task.groupId }&name=${ task.name }&projectId=${ task.projectId }`)
}

// 下载文件
const handleFileDownload = () => {
  const downloadProgress = ref(0)
  const id = requireDetailsResponse.value.id
  const fileName = requireDetailsResponse.value.name + (requireDetailsResponse.value.documentPath.substring(requireDetailsResponse.value.documentPath.lastIndexOf('.')))
  const notice = ElNotification({
    title: '下载进度',
    position: 'bottom-right',
    duration: 0,
    showClose: false,
    message: h(Progress, {
      progress: downloadProgress,
      type: '0',
      fileName: fileName,
      onComplete(status) {
        if ('1' === status) {
          setTimeout(() => {
            notice.close()
          }, 3000)
        }
      }
    })
  })
  downLoadRequireDocumentApi({id}, (e) => {
    downloadProgress.value = Math.floor(e.loaded * 100 / e.total)
  }).then(res => {
    // 将返回的数据通过Blob的构造方法，创建Blob对象
    console.log(res.headers)
    const blob = new Blob([res])
    if ('msSaveOrOpenBlob' in navigator) {
      window.navigator.msSaveOrOpenBlob(blob, fileName) // 针对浏览器
    } else {
      // 创建a标签
      const elink = document.createElement('a')
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      // 移除链接
      URL.revokeObjectURL(elink.href)
      // 移除a标签
      document.body.removeChild(elink)
    }
    downloadProgress.value = 100
  })
}

const deleteRequireDocument = () => {
  deleteRequireDocumentApi({id: requireDetailsResponse.value.id}).then(res => {
    findRequireDetailsApi({id: query.id}).then(({data}) => {
      requireDetailsRequest.value.name = data.name
      requireDetailsRequest.value.owner = data.owner.id
      requireDetailsRequest.value.task = data.task
      requireDetailsRequest.value.id = data.id
      requireDetailsRequest.value.status = data.status
      requireDetailsRequest.value.startTime = dayjs(data.startTime).format('YYYY-MM-DD HH:mm:ss')
      requireDetailsRequest.value.endTime = dayjs(data.endTime).format('YYYY-MM-DD HH:mm:ss')
      requireDetailsRequest.value.description = data.description
      requireDetailsRequest.value.priority = data.priority
      requireDetailsRequest.value.scheme = data.scheme
      requireDetailsResponse.value = data
      console.log(data)
    })
  })
}

const documentFileUploadRequest = ref({})
const projectImageFileRef = ref()
const onImageFileExceed = (files) => {
  const file = files[0]
  file.uid = genFileId()
  projectImageFileRef.value.clearFiles()
  projectImageFileRef.value.handleStart(file)
}
const onChangeImageFileUpload = (uploadFile) => {
  documentFileUploadRequest.value.id = requireDetailsResponse.value.id
  documentFileUploadRequest.value.documentFile = uploadFile.raw
  addRequireDocumentApi(documentFileUploadRequest.value).then(res => {
    findRequireDetailsApi({id: query.id}).then(({data}) => {
      requireDetailsRequest.value.name = data.name
      requireDetailsRequest.value.owner = data.owner.id
      requireDetailsRequest.value.task = data.task
      requireDetailsRequest.value.id = data.id
      requireDetailsRequest.value.status = data.status
      requireDetailsRequest.value.startTime = dayjs(data.startTime).format('YYYY-MM-DD HH:mm:ss')
      requireDetailsRequest.value.endTime = dayjs(data.endTime).format('YYYY-MM-DD HH:mm:ss')
      requireDetailsRequest.value.description = data.description
      requireDetailsRequest.value.priority = data.priority
      requireDetailsRequest.value.scheme = data.scheme
      requireDetailsResponse.value = data
      console.log(data)
    })
  })
}

const deleteRequire = () => {
  ElMessageBox.confirm(
      '请确认是否删除需求',
      '删除需求',
      {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }
  )
      .then(() => {
        deleteRequireApi({id: requireDetailsResponse.value.id}).then(res => {
          ElMessage({
            type: 'info',
            message: '删除成功',
          })
          router.back()
        })
      }).catch((action) => {

  })
}

</script>

<template>
  <el-breadcrumb separator="/" style="margin-bottom: 36px;">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item :to="{ path: `/system/projectManagement/projectTask`, query: {id: query.projectId}}">项目任务
    </el-breadcrumb-item>
    <el-breadcrumb-item
        :to="{ path: '/system/projectManagement/projectTask/projectTaskDetails', query: {id: query.id, projectId: query.projectId, name: query.name, taskId: query.taskId, groupId: query.groupId}}">
      {{ query.name }}
    </el-breadcrumb-item>
    <el-breadcrumb-item>{{ query.requireName }}</el-breadcrumb-item>
  </el-breadcrumb>
  <el-steps
      style="width: 100%;"
      space="33%"
      :active="requireDetailsResponse.status === 3 ? 3 : requireDetailsResponse.status + 1"
      finish-status="success"
      align-center
  >
    <el-step title="已排期">
      <!--      <template #title>-->
      <!--        <div style="font-size: 14px">-->
      <!--          未开始-->
      <!--        </div>-->
      <!--      </template>-->
      <template #description>
        <div v-if="requireDetailsResponse.status === 0">
          最近更新时间：{{ dayjs(requireDetailsResponse.updateTime).format('YYYY/MM/DD HH:mm') }}
        </div>
      </template>
    </el-step>
    <el-step title="进行中">
      <template #description>
        <div v-if="requireDetailsResponse.status === 1">
          最近更新时间：{{ dayjs(requireDetailsResponse.updateTime).format('YYYY/MM/DD HH:mm') }}
        </div>
      </template>
    </el-step>
    <el-step title="已完成" v-if="requireDetailsResponse.status !== 3">
      <template #description>
        <div v-if="requireDetailsResponse.status === 2">
          实际完成时间：{{ dayjs(requireDetailsResponse.updateTime).format('YYYY/MM/DD HH:mm') }}
        </div>
      </template>
    </el-step>
    <el-step title="已延期" v-if="requireDetailsResponse.status === 3">
      <template #description>
        <div>
          预计完成时间：{{ dayjs(requireDetailsResponse.endTime).format('YYYY/MM/DD HH:mm') }}
        </div>
      </template>
    </el-step>
  </el-steps>

  <div style="padding: 24px 220px;">
    <div style=" margin-bottom: 36px;">

      <el-form label-position="left" label-width="auto">
        <div style="margin-bottom: 24px; display: flex; justify-content: space-between;">
          <span style="font-size: 18px;">基本信息</span>
          <div>
            <el-button v-if="requireDetailsResponse.opearateAuth === 1 && !editDisable" @click="editDisable = true"
                       size="small" type="danger">取消
            </el-button>
            <el-button v-if="requireDetailsResponse.opearateAuth === 1 && editDisable" @click="editDisable = false"
                       size="small" type="primary">编辑
            </el-button>
            <el-button v-else-if="requireDetailsResponse.opearateAuth === 1 && !editDisable"
                       @click="onRequireDetailsSubmit" size="small" type="primary">确认
            </el-button>
          </div>
        </div>
        <div class="form-wrap">
          <div class="form-wrap__left">
            <el-form-item label="需求名">
              <el-input :disabled="editDisable" style="width: 240px;" v-model="requireDetailsRequest.name"
                        placeholder="输入项目名称" clearable />
            </el-form-item>
            <el-form-item label="负责人">
              <el-select
                  v-model="requireDetailsRequest.owner"
                  :remote-method="onOwnerRemoteMethod"
                  placeholder="搜索负责人"
                  :loading="ownerSearchLoading"
                  style="width: 240px"
                  clearable
                  filterable
                  remote
                  :disabled="editDisable"
              >
                <el-option
                    v-for="owner in ownerList"
                    :key="owner.id"
                    :label="owner.name"
                    :value="owner.id"
                >
                  <span style="float: left">{{ owner.name }}</span>
                  <span
                      style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">
                {{ owner.username }}
            </span>
                </el-option>
              </el-select>
              <!--              <el-input :disabled="editDisable" style="width: 240px;" v-model="requireDetailsRequest.owner"-->
              <!--                        placeholder="" clearable/>-->
            </el-form-item>
            <el-form-item label="需求状态" prop="status" style="margin-right: 0">
              <el-select
                  v-model="requireDetailsRequest.status"
                  style="width: 240px"
                  :disabled="editDisable"
              >
                <el-option label="已排期" :value="0" />
                <el-option label="进行中" :value="1" />
                <el-option label="已完成" :value="2" />
                <el-option label="已延期" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="需求优先级" prop="priority" style="margin-right: 0">
              <el-select
                  v-model="requireDetailsRequest.priority"
                  style="width: 240px"
                  :disabled="editDisable"
              >
                <el-option label="低" :value="0" />
                <el-option label="中" :value="1" />
                <el-option label="高" :value="2" />
              </el-select>
            </el-form-item>
            <div v-if="requireDetailsResponse.opearateAuth === 1">
              <el-form-item v-if="requireDetailsResponse.documentPath" label="需求文档" prop="priority"
                            style="margin-right: 0">
                <el-button style="width: 114px;" @click="handleFileDownload">下载</el-button>
                <el-button style="width: 114px;" type="danger" @click="deleteRequireDocument">删除</el-button>
              </el-form-item>
              <el-form-item v-else label="需求文档" prop="priority" style="margin-right: 0">
                <el-upload action="#"
                           :limit="1"
                           :on-exceed="onImageFileExceed"
                           :on-change="onChangeImageFileUpload"
                           ref="projectImageFileRef"
                           accept=".doc,.docx,.pdf,.txt"
                           :auto-upload="false">
                  <el-button style="width: 240px" :icon="IconPlus">上传</el-button>
                </el-upload>
              </el-form-item>
            </div>
            <div v-else-if="requireDetailsResponse.documentPath">
              <el-form-item label="需求文档" prop="documentFile" style="margin-right: 0">
                <el-button style="width: 240px;" @click="handleFileDownload">下载</el-button>
              </el-form-item>
            </div>


            <!--              <el-input :disabled="editDisable" style="width: 240px;" v-model="requireDetailsRequest.startTime"-->
            <!--                        placeholder="" clearable/>-->

          </div>
          <div class="form-wrap__right">
            <el-form-item label="创建人">
              <el-input :disabled="true" style="width: 240px;" v-model="requireDetailsResponse.creator.name"
                        placeholder="" clearable />
            </el-form-item>
            <el-form-item label="所属任务">
              <el-button @click="GoTo(requireDetailsRequest.task)" :icon="IconLink" type="primary"
                         style="width: 240px;">
                {{ requireDetailsRequest.task.name }}
              </el-button>
            </el-form-item>
            <el-form-item label="需求创建时间">
              <el-date-picker
                  v-model="requireDetailsRequest.startTime"
                  type="datetime"
                  placeholder="选择时间"
                  :disabled="editDisable"
                  style="width: 240px;"
              />
            </el-form-item>
            <el-form-item label="预计结束时间">
              <el-date-picker
                  v-model="requireDetailsRequest.endTime"
                  type="datetime"
                  placeholder="选择时间"
                  :disabled="editDisable"
                  style="width: 240px;"
              />
            </el-form-item>
          </div>
        </div>
        <div style=" margin-bottom: 36px;">
          <div style="margin-bottom: 24px; display: flex; justify-content: space-between;">
            <span style="font-size: 18px;">需求描述</span>
          </div>
          <el-form-item>
            <el-input type="textarea" rows="4" :disabled="editDisable" v-model="requireDetailsRequest.description"
                      placeholder="输入需求描述" clearable :autosize="{minRows: 4, maxRows: 12}" />
          </el-form-item>
        </div>
        <div style=" margin-bottom: 36px;">
          <div style="margin-bottom: 24px; display: flex; justify-content: space-between;">
            <span style="font-size: 18px;">需求方案</span>
            <div>
              <el-button type="primary" size="small"
                         v-if="schemeDisable && userStore.userInfo.id === requireDetailsRequest.owner"
                         @click="schemeDisable = false"
              >
                编辑
              </el-button>
              <el-button type="danger" size="small" v-if="!schemeDisable" @click="schemeDisable = true">取消</el-button>
              <el-button type="primary" size="small" v-if="!schemeDisable" @click="onRequireSchemeSubmit">确认
              </el-button>
            </div>
          </div>
          <el-form-item>
            <el-input type="textarea" rows="4" :disabled="schemeDisable" v-model="requireDetailsRequest.scheme"
                      placeholder="输入需求方案" clearable :autosize="{minRows: 4, maxRows: 12}" />
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div style="display: flex; justify-content: center;">
      <el-button @click="deleteRequire" v-if="requireDetailsResponse.opearateAuth === 1" type="danger"
                 style="width: 200px;">删除需求
      </el-button>
    </div>

  </div>
</template>

<style scoped lang="less">
.form-wrap {
  display: flex;
  justify-content: space-between;

  .form-wrap__left {
    //flex: 1;
  }

  .form-wrap__right {
    //flex: 1;
  }
}

:deep(.el-textarea__inner) {
  resize: none;
}
</style>